<template>
  <div class="device-management">
    <!-- 主体内容区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📱 设备管理</span>
          <div class="header-actions">
            <div class="record-stats">
              <el-tag type="info">共 {{ total }} 台设备</el-tag>
            </div>
            <div class="action-buttons">
              <el-button type="primary" @click="handleAdd" :icon="Plus">
                ➕ 新增设备
              </el-button>
            </div>
          </div>
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          :height="tableHeight"
          class="custom-table"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="deviceName" label="设备名称" width="180" show-overflow-tooltip />
          <el-table-column prop="deviceId" label="设备ID" width="160" show-overflow-tooltip />
          <el-table-column prop="deviceType" label="设备类型" width="200" show-overflow-tooltip />
          <el-table-column prop="deviceBluetoothName" label="蓝牙名称" width="180" show-overflow-tooltip />
          <el-table-column prop="ipaName" label="IPA名称" width="160" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="searchTime" label="搜索时间" width="100" align="center">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.searchTime }}s</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                ✏️ 编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                🗑️ 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pageCurrent"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑设备弹窗 -->
    <el-dialog
      v-model="showDeviceModal"
      :title="isEdit ? '✏️ 编辑设备' : '➕ 新增设备'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="deviceForm" :rules="deviceRules" ref="deviceFormRef" label-width="120px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="deviceForm.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="deviceForm.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-input v-model="deviceForm.deviceType" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="蓝牙名称" prop="deviceBluetoothName">
          <el-input v-model="deviceForm.deviceBluetoothName" placeholder="请输入蓝牙名称" />
        </el-form-item>
        <el-form-item label="IPA名称" prop="ipaName">
          <el-input v-model="deviceForm.ipaName" placeholder="请输入IPA名称" />
        </el-form-item>
        <el-form-item label="IPA ID" prop="ipaId">
          <el-input v-model="deviceForm.ipaId" placeholder="请输入IPA ID" />
        </el-form-item>
        <el-form-item label="搜索时间(秒)" prop="searchTime">
          <el-input-number v-model="deviceForm.searchTime" :min="1" :max="60" placeholder="搜索时间" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDeviceModal">取消</el-button>
          <el-button type="primary" @click="confirmDevice" :loading="confirmLoading">
            {{ confirmLoading ? '保存中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { queryDeviceListPage, addDevice, updateDevice, deleteDevice } from '../api/business.js'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const pageCurrent = ref(1)

// 弹窗相关
const showDeviceModal = ref(false)
const isEdit = ref(false)
const confirmLoading = ref(false)
const deviceFormRef = ref()

// 设备表单
const deviceForm = reactive({
  id: null,
  deviceName: '',
  deviceId: '',
  deviceType: '',
  deviceBluetoothName: '',
  ipaName: '',
  ipaId: '',
  searchTime: 5
})

// 表单验证规则
const deviceRules = {
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  deviceId: [
    { required: true, message: '请输入设备ID', trigger: 'blur' }
  ],
  deviceType: [
    { required: true, message: '请输入设备类型', trigger: 'blur' }
  ],
  searchTime: [
    { required: true, message: '请输入搜索时间', trigger: 'blur' }
  ]
}

// 加载管理器
let loadingInstance = null
const showLoading = (text = '加载中...') => {
  if (loadingInstance) {
    loadingInstance.close()
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 计算表格高度
const tableHeight = computed(() => {
  return 'calc(100vh - 280px)'
})

// 获取设备列表数据
const getData = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNum: pageCurrent.value,
      pageSize: pageSize.value
    }
    
    const res = await queryDeviceListPage(params)
    console.info('设备列表数据:', res)
    
    if (res && res.success === true && res.content) {
      tableData.value = res.content.list || []
      total.value = res.content.total || 0
      
      ElMessage.success(`📱 成功获取${tableData.value.length}台设备`)
    } else {
      throw new Error(res?.message || '数据格式错误')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error(error.data?.message || '获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  getData()
}

const handleCurrentChange = (page) => {
  pageCurrent.value = page
  getData()
}

// 重置表单
const resetDeviceForm = () => {
  deviceForm.id = null
  deviceForm.deviceName = ''
  deviceForm.deviceId = ''
  deviceForm.deviceType = ''
  deviceForm.deviceBluetoothName = ''
  deviceForm.ipaName = ''
  deviceForm.ipaId = ''
  deviceForm.searchTime = 5
}

// 新增设备
const handleAdd = () => {
  isEdit.value = false
  resetDeviceForm()
  showDeviceModal.value = true
}

// 编辑设备
const handleEdit = (row) => {
  isEdit.value = true
  deviceForm.id = row.id
  deviceForm.deviceName = row.deviceName || ''
  deviceForm.deviceId = row.deviceId || ''
  deviceForm.deviceType = row.deviceType || ''
  deviceForm.deviceBluetoothName = row.deviceBluetoothName || ''
  deviceForm.ipaName = row.ipaName || ''
  deviceForm.ipaId = row.ipaId || ''
  deviceForm.searchTime = row.searchTime || 5
  showDeviceModal.value = true
}

// 删除设备
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除设备 "${row.deviceName}" 吗？删除后无法恢复。`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    showLoading('删除中...')
    
    // 使用批量删除接口，传入数组格式的ID
    const res = await deleteDevice([row.id])
    
    hideLoading()
    
    // 检查接口返回的success字段
    if (res && res.success === true) {
      ElMessage.success('✅ 删除成功')
      
      // 刷新列表
      setTimeout(() => {
        getData()
      }, 500)
    } else {
      // 接口返回失败
      throw new Error(res?.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      hideLoading()
      console.error('删除设备失败:', error)
      ElMessage.error('❌ ' + (error.message || error.data?.message || '删除失败'))
    }
  }
}

// 关闭弹窗
const closeDeviceModal = () => {
  showDeviceModal.value = false
  resetDeviceForm()
  if (deviceFormRef.value) {
    deviceFormRef.value.clearValidate()
  }
}

// 确认保存设备
const confirmDevice = async () => {
  if (!deviceFormRef.value) return
  
  try {
    await deviceFormRef.value.validate()
    
    confirmLoading.value = true
    showLoading(isEdit.value ? '更新中...' : '保存中...')
    
    const deviceData = {
      deviceName: deviceForm.deviceName,
      deviceId: deviceForm.deviceId,
      deviceType: deviceForm.deviceType,
      deviceBluetoothName: deviceForm.deviceBluetoothName,
      ipaName: deviceForm.ipaName,
      ipaId: deviceForm.ipaId,
      searchTime: deviceForm.searchTime
    }
    
    let res
    if (isEdit.value) {
      deviceData.id = deviceForm.id
      res = await updateDevice(deviceData)
    } else {
      res = await addDevice(deviceData)
    }
    
    hideLoading()
    
    // 检查接口返回的success字段
    if (res && res.success === true) {
      ElMessage.success(isEdit.value ? '✅ 更新成功' : '✅ 新增成功')
      closeDeviceModal()
      
      // 刷新列表
      setTimeout(() => {
        getData()
      }, 500)
    } else {
      // 接口返回失败
      throw new Error(res?.message || (isEdit.value ? '更新失败' : '新增失败'))
    }
    
  } catch (error) {
    hideLoading()
    if (error.message && error.message.includes('请输入')) {
      // 表单验证错误，不显示错误消息
      return
    }
    
    console.error('保存设备失败:', error)
    
    // 显示详细错误信息
    let errorMessage = error.message || error.data?.message || '保存失败'
    if (errorMessage.includes('ipa_run_time')) {
      errorMessage = '缺少必要的运行时间字段，请联系技术支持'
    }
    
    ElMessage.error('❌ ' + errorMessage)
  } finally {
    confirmLoading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  getData()
})
</script>

<style scoped>
.device-management {
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 70px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e40af;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.record-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.custom-table {
  width: 100%;
  flex: 1;
}

.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  z-index: 10;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-table__body-wrapper) {
  /* 只在需要时显示滚动条 */
  overflow-y: auto !important;
  overflow-x: hidden !important;
  max-height: calc(100vh - 350px) !important;
  /* 为底部分页器预留更多空间，避免遮挡 */
  padding-bottom: 10px !important;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s ease;
  min-height: 20px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-corner {
  background: #f5f5f5;
}

/* 表格横向铺满 */
:deep(.el-table) {
  width: 100% !important;
  min-width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 确保表格内容不会超出容器 */
:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格内容溢出处理 */
:deep(.el-table .cell) {
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 确保最后一行数据不被遮挡 */
:deep(.el-table__body tr:last-child td) {
  border-bottom: 1px solid #ebeef5;
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .device-management {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>